﻿using System;
using System.Collections.Generic;
using System.Web;

namespace Popw.LiveBlog.Repositories.Cache
{
	public class LocalCacheProvider : ICacheProvider
	{
		public LocalCacheProvider()
		{
			_cache = HttpRuntime.Cache;
		}

		private readonly System.Web.Caching.Cache _cache;

		public void Add(string key, object item, int duration)
		{
			_cache.Insert(key, item, null, DateTime.UtcNow.AddMilliseconds(duration), System.Web.Caching.Cache.NoSlidingExpiration);
		}

		public T Get<T>(string key) where T : class
		{
			return _cache[key] as T;
		}

		public T? GetValue<T>(string key) where T : struct
		{
			var cachedObject = _cache[key];
			if (cachedObject == null)
				return null;
			return (T)cachedObject;
		}

		public void Remove(string key)
		{
			_cache.Remove(key);
		}

		public void Clear()
		{
			var list = new List<string>();
			var keys = _cache.GetEnumerator();
			while (keys.MoveNext())
				list.Add(keys.Key.ToString());
			foreach (var item in list)
				_cache.Remove(item);
		}
	}
}